package com.example.order.message;

import com.example.order.dataObject.ProductInfoOutput;
import com.example.order.util.Console;
import com.example.order.util.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ProductInfoReceiver {

    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String msg) throws JsonProcessingException {
        List<ProductInfoOutput> list = (List<ProductInfoOutput>) JsonUtils.toObject(msg, new TypeReference<List<ProductInfoOutput>>(){});

        //存到redis里面,库存
        for (ProductInfoOutput model:list){
            stringRedisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE,model.getProductId()),model.getProductStock().toString());
            Console.log("productInfo",model);
        }
    }

}
